package aaa;

import java.awt.Button;
import java.io.BufferedReader;  
import java.io.IOException;  
import java.io.InputStream;  
import java.io.InputStreamReader;  
import java.io.OutputStream;
import java.lang.reflect.Array;
import java.net.ConnectException;  
import java.net.HttpURLConnection;  
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import com.google.gson.Gson;
import com.google.gson.JsonElement;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import tree.TreeNode;
import tree.TreeNodeMerger;  
/** 
 * 发起http请求并获取结果  
 * @author zyz 
 * @date 20140522 
 * 
 */  
public class HttpRequestUtil {  
    /**  
     * 发起http请求并获取结果  
     *   
     * @param requestUrl 请求地址  
     * @param requestMethod 请求方式（GET、POST）  
     * @param outputStr 提交的数据  
     * @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)  
     */    
    public static JSONArray httpRequest(String requestUrl, String requestMethod, String outputStr) {    
        JSONObject jsonObject = null; 
        JSONArray jsonArray = null;
        StringBuffer buffer = new StringBuffer();  
        InputStream inputStream=null;  
        try {  
            URL url = new URL(requestUrl);  
            HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();    
            httpUrlConn.setDoOutput(true);    
            httpUrlConn.setDoInput(true);    
            httpUrlConn.setUseCaches(false);  
            // 设置请求方式（GET/POST）    
            httpUrlConn.setRequestMethod(requestMethod);    
            if ("GET".equalsIgnoreCase(requestMethod))    
                httpUrlConn.connect();    
    
            // 当有数据需要提交时    
            if (null != outputStr) {    
                OutputStream outputStream = httpUrlConn.getOutputStream();    
                // 注意编码格式，防止中文乱码    
                outputStream.write(outputStr.getBytes("UTF-8"));    
                outputStream.close();    
            }  
            //将返回的输入流转换成字符串    
            inputStream = httpUrlConn.getInputStream();    
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");    
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);    
    
            String str = null;    
            while ((str = bufferedReader.readLine()) != null) {    
                buffer.append(str);    
            }    
            bufferedReader.close();    
            inputStreamReader.close();    
            // 释放资源    
            inputStream.close();    
            inputStream = null;    
            httpUrlConn.disconnect();    
//          jsonObject = JSONObject.fromObject(buffer.toString());
            jsonArray = JSONArray.fromObject(buffer.toString());
        } catch (ConnectException ce) {    
              ce.printStackTrace();  
              System.out.println("Weixin server connection timed out");  
        } catch (Exception e) {    
               e.printStackTrace();  
               System.out.println("http request error:{}");  
        }finally{  
            try {  
                if(inputStream!=null){  
                    inputStream.close();  
                }  
            } catch (IOException e) {  
                // TODO Auto-generated catch block  
                e.printStackTrace();  
            }  
        }   
        return jsonArray;    
    }    
    
    
  public static void main(String[] args)
  {
		String requestUrl = "https://isisn.nsfc.gov.cn/egrantindex/cpt/ajaxload-tree?locale=zh_CN&key=subject_code_index&cacheable=true&sqlParamVal=";
		String requestMethod = "GET";
		String outputStr = null;
		// JSONObject jsonObject = new HttpRequestUtil().httpRequest(requestUrl, requestMethod, outputStr);
		JSONArray jsonArray = new HttpRequestUtil().httpRequest(requestUrl, requestMethod, outputStr);
		System.out.println("执行完http请求后，拿到的json数组为：" + jsonArray);
		System.out.println(jsonArray.size());
		
		// jsonArray---->treenode的list
		List<TreeNode> treeNodes = JSONArray.toList(jsonArray, TreeNode.class);// 执行完后，treeNodes是一个list，里面没有填充children。
		System.out.println("把拿到的json数组转为指定结构TreeNode的list，里面没有填充children。 " + treeNodes);

		// 添加一个root到位置0
		TreeNode root = new TreeNode();
		root.setId("0");
		root.setName("根节点");
		root.setTitle("根节点");
		root.setPid("-1");
//		treeNodes.add(0, root);

		TreeNode treeNodeMerger = TreeNodeMerger.merge(treeNodes);// 执行完后，treeNodes还是一个list，但是里面的children已经填充完毕。
		System.out.println("执行完TreeNodeMerger.merge(treeNodes)后，treeNodes里面会自动填充好children。" + treeNodes);

		JSONArray jsonArray3 = JSONArray.fromObject(treeNodeMerger);
		System.out.println("1111111111111" + jsonArray3);

		System.exit(0);

		
		
		
		TreeNode[] treeNodes2 = new TreeNode[10];
		/*
		 * treeNodes2[0] = new TreeNode("1", "", "0");
		 * treeNodes2[1] = new TreeNode("2", "", "1"); treeNodes2[2] = new TreeNode("3", "", "1");
		 * treeNodes2[3] = new TreeNode("4", "", "2"); treeNodes[4] = new TreeNode("5", "", "3");
		 * treeNodes[5] = new TreeNode("6", "", "4"); treeNodes[6] = new TreeNode("7",
		 * "", "3"); treeNodes[7] = new TreeNode("8", "", "5"); treeNodes[8] = new
		 * TreeNode("9", "", "6"); treeNodes[9] = new TreeNode("10", "", "9");
		 */
		TreeNode treeNode = TreeNodeMerger.merge(jsonArray);
		JSONArray jsonArray2 = JSONArray.fromObject(treeNode);
		System.out.println("22222222222222222222" + jsonArray2);
}
  
}